package com.siyoumi.app.modules.iot.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siyoumi.app.entity.IotDevice;
import com.siyoumi.app.modules.iot.service.SvcIotDevice;
import com.siyoumi.app.netty.NettyMqttUtil;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XApp;
import com.siyoumi.util.XReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wxapp/iot/api")
public class ApiIot
        extends ApiIotBase {
    /**
     * 获取设备key
     */
    @GetMapping("get_device_key")
    public XReturn getDeviceKey() {
        IotDevice entityDevice = getDevice(false);
        //判断未激活状态，已激活，要去后台改为未激活

        //更新设备key
        String newKey = XApp.getUUID();
        IotDevice entityUpdate = new IotDevice();
        entityUpdate.setIdev_id(entityDevice.getKey());
        entityUpdate.setIdev_key(newKey);
        SvcIotDevice.getApp().updateById(entityUpdate);

        //删除mqtt队列
        String id = SvcIotDevice.getBean().getMqttQueueId(entityDevice);
        NettyMqttUtil.getMapChannel().remove(id);

        getR().setData("device_key", newKey);
        return getR();
    }

    @GetMapping("device_list")
    public XReturn deviceList() {
        String[] select = {
                "idev_id",
                "idev_pro_id",
                "idev_num",
                "ipro_name",
        };
        JoinWrapperPlus<IotDevice> query = SvcIotDevice.getBean().listQuery();
        query.select(select);
        query.orderByAsc("idev_order")
                .orderByDesc("idev_create_date");

        IPage<IotDevice> page = new Page<>(getPageIndex(), getPageSize(), false);
        IPage<Map<String, Object>> list = SvcIotDevice.getApp().getMaps(page, query);

        getR().setData("list", list.getRecords());
        return getR();
    }
}
